package UDP;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class UdpEchoClient {
     DatagramSocket socket=null;
    String ip="";
    int port=0;
    public UdpEchoClient(String ip,int port) throws SocketException {
        socket=new DatagramSocket();
        this.ip=ip;
        this.port=port;
    }
    //客户端启动
    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while (true){
            System.out.println("->");
            //控制台输入数据作为请求
            String request=scanner.next();
            //发送请求
            DatagramPacket requestpacket=new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(ip),port);
            socket.send(requestpacket);
            //读取响应
            DatagramPacket responsepacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsepacket);
            //打印响应
            String response=new String(responsepacket.getData(),0,responsepacket.getLength());
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient=new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
